package stripepay

import (
	"errors"
	"simplifly-tech/payment/consts"
	"simplifly-tech/payment/internal"
	model2 "simplifly-tech/payment/model"
	"simplifly-tech/utility/log"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"github.com/stripe/stripe-go/v80"
	"github.com/stripe/stripe-go/v80/webhook"
)

func (stripeService *StripeService) Notify(ctx *gin.Context) (*model2.PaymentNotification, error) {

	body, err := ctx.GetRawData()

	// 获取Stripe-Signature header
	signature := ctx.GetHeader("Stripe-Signature")
	// 验证Webhook签名
	event, err := webhook.ConstructEventWithOptions(
		body,
		signature,
		stripeService.WebhookKey,
		webhook.ConstructEventOptions{
			Tolerance:                30 * time.Minute,
			IgnoreAPIVersionMismatch: true,
		},
	)
	if err != nil {
		// 验证失败，返回400错误
		return nil, errors.New("Webhook signature verification failed")
	}

	// 处理事件
	switch event.Type {
	case "payment_intent.succeeded":
		// 处理支付成功的逻辑
		var paymentIntent stripe.PaymentIntent
		err := json.Unmarshal(event.Data.Raw, &paymentIntent)
		if err != nil {
			log.Errorf("err :%v", json.Unmarshal(event.Data.Raw, &paymentIntent))
			return nil, errors.New("Webhook unmarshal failed")
		}
		orderId, exists := paymentIntent.Metadata["order_id"]
		if exists == false {
			log.Errorf("paymentIntent.Metadata[\"order_id\"] err Webhook order_id does not exist")
			return nil, errors.New("Webhook order_id does not exist")
		}
		incomeIdStr, exists := paymentIntent.Metadata["income_id"]

		paidAt, _ := time.Parse("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:04:05"))
		incomeId, _ := strconv.ParseUint(incomeIdStr, 10, 64) //o

		return &internal.PaymentNotification{
			Status:       consts.NotifyStatusSuccess,
			OrderID:      orderId,
			IncomeID:     uint(incomeId),
			PaidAt:       paidAt,
			AsyncPayment: true,
		}, nil

	}

	return nil, errors.New("pay is fail")
}
